import React, { Component } from "react";
import "./05.css";

class Child extends Component {
  render() {
    let { title, score } = this.props;
    return (
      <div
        className="child"
        onClick={() => {
          bus.publish(this.props);
        }}
      >
        <div className="left"></div>
        <div className="right">
          <div>{title}</div>
          <div>{score}</div>
        </div>
      </div>
    );
  }
}

class Detail extends Component {
  state = {
    val: {},
  };
  render() {
    bus.subscribe((value) => {
      this.setState({
        val: value,
      });
    });
    return (
      <div className="detail">
        <div>{this.state.val.title}</div>
        <div>{this.state.val.score}</div>
      </div>
    );
  }
}

export default class App extends Component {
  state = {
    list: [
      {
        title: "第一个列表",
        score: "88分",
      },
      {
        title: "第二个列表",
        score: "88分",
      },
      {
        title: "第三个列表",
        score: "88分",
      },
    ],
    value: {},
  };
  render() {
    return (
      <div>
        {this.state.list.map((item, index) => {
          return <Child {...item} key={index} />;
        })}
        <Detail />
      </div>
    );
  }
}

let bus = {
  // 列表
  list: [],
  // 订阅
  subscribe(callback) {
    this.list.push(callback);
  },
  // 发布
  publish(val) {
    this.list.forEach((callback) => {
      callback && callback(val);
    });
  },
};
bus.subscribe((val) => {
  console.log("999", val);
});
bus.subscribe((val) => {
  console.log("222", val);
});
bus.publish("传过");
